package app.server.project.main.service.db.dao.user;


import app.server.project.main.service.db.entity.user.UserRaceEntity;
import app.server.project.main.service.db.mapper.user.UserRaceMapper;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;

import java.util.List;

@RequiredArgsConstructor
@Repository
public class UserRaceDao extends ServiceImpl<UserRaceMapper, UserRaceEntity> {


    @Cacheable(key = "#userId", cacheNames = "app.server.project.main.service.db.dao.UserRaceDao")
    public List<UserRaceEntity> getRaceInfo(long userId) {
        var data = this.list(Wrappers.<UserRaceEntity>lambdaQuery().eq(UserRaceEntity::getUserId, userId));
        data.forEach(v -> {
            v.setSynDb(true);
        });
        return data;
    }

    public UserRaceEntity getOne(List<UserRaceEntity> list, int raceId, long userId) {
        UserRaceEntity userRaceEntity = null;
        var val = list.stream().filter(v -> v.getRaceId() == raceId).findAny();
        if (val.isPresent()) return val.get();
        userRaceEntity = UserRaceEntity.of(userId, raceId, IdUtil.getSnowflakeNextId());
        list.add(userRaceEntity);
        return userRaceEntity;
    }

}
